<template>
   <el-card v-loading="loading">
       <template #header>
           <span>添加班级</span>
       </template>
        <!-- ref="form":对当前对象的获取，通过$获取当前对象 -->
       <el-form ref="form" :model="form" :rules="rules" label-width="80px">
           <el-form-item label="班级期号" prop="class_name">
               <el-input v-model="form.class_name"></el-input>
           </el-form-item>
           <el-form-item label="状态" prop="status">
              <el-radio v-model="form.status" label="1">显示</el-radio>
              <el-radio v-model="form.status" label="0">隐藏</el-radio>
           </el-form-item>
           <el-form-item>
               <el-button type="primary" @click="add()">立即创建</el-button>
               <el-button @click="back()">返回</el-button>
           </el-form-item>
       </el-form>
   </el-card>
</template>

<script>
export default {
  data() {
      const isClassSame = async (rule,value,callback)=>{
        var {data}=await this.axios({
             method:'get',
             url:`/classes/exists/class_name/${value}`
         });
         if(data){
             callback(new Error('班级期名已存在'))
         }else{
             callback();
         }
      };
    return {
      loading:false,  
      form: {
        class_name: "",
        status:""
      },
      rules: {
        class_name: [
          { required: true, message: "班级期名必须填写！" },
          {
            validator: (rule, value, callback) => {
              if (/^[0-9]*$/.test(value)) {
                callback();
              } else {
                callback(new Error("班级期号必须是数字"));
              }
            }
          },
          {validator:isClassSame}
        ],
      }
    };
  },
  methods: {
   async add() {
       await this.$refs.form.validate((flag)=>{
            if(!flag){return;}
            this.loading=true;
            this.axios({
                method:'post',
                url:'/classes/add',
                data:{
                    class_name:this.form.class_name,
                    status: this.form.status,
                }
            });
            this.loading=false;
            this.$message.success('添加成功');
            this.$refs.form.resetFields();
        })
    },
    back() {
      this.$router.push({ path: "home/classes" });
    }
  }
};
</script>


